package com.tender;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * 三个线程交替打印 A、B、C
 */
public class ThreadTasks {

    private static volatile int status = 0;

    private static final int NUM = 100;
    public static void main(String[] args) throws Exception {
        Phaser phaser = new Phaser(3);

        new Thread(() -> printA(phaser)).start();
        new Thread(() -> printB(phaser)).start();
        new Thread(() -> printC(phaser)).start();

        phaser.awaitAdvanceInterruptibly(phaser.getPhase(), 10, TimeUnit.MINUTES);
    }

    private static void printA(Phaser phaser) {
        try {
            for (int i = 0; i < NUM ; i++) {
                while (0 != status) {
                    // Thread.yield(); // 让出cpu 会导致上线文的切换，不是很好
                }
                System.out.println("A");
                status = 2;
            }
        } finally {
            phaser.arrive();
        }
    }

    private static void printB(Phaser phaser) {
        try {
            for (int i = 0; i < NUM ; i++) {
                while (2 != status) {
                    // Thread.yield();
                }
                System.out.println("B");
                status = 4;
            }
        } finally {
            phaser.arrive();
        }
    }

    private static void printC(Phaser phaser) {
        try {
            for (int i = 0; i < NUM ; i++) {
                while (4 != status) {
                    // Thread.yield();
                }
                System.out.println("C");
                status = 0;
            }
        } finally {
            phaser.arrive();
        }
    }

}
